package main

import (
	"context"
	"developer_tools/internal/httpClient"
)

// HTTPApp 结构体
type HTTPApp struct {
	ctx        context.Context
	cancelFunc context.CancelFunc
}

// NewHTTPApp 创建一个新的HTTPApp
func NewHTTPApp() *HTTPApp {
	return &HTTPApp{}
}

// 启动时被调用
func (h *HTTPApp) startup(ctx context.Context) {
	h.ctx = ctx
}

// 关闭时被调用
func (h *HTTPApp) shutdown() {
	log_.Info("[HTTPApp] Shutting down...")
}

// SendRequest 发送HTTP请求
func (h *HTTPApp) SendRequest(request httpClient.HTTPRequest) (*httpClient.HTTPResponse, error) {
	log_.Debugf("Sending HTTP request: %+v", request)
	ctx, cancel := context.WithCancel(context.Background())
	h.cancelFunc = cancel

	response, err := httpClient.SendRequest(request, ctx)
	if err != nil {
		log_.Errorf("Failed to send HTTP request: %v", err)
		return nil, err
	}

	log_.Debugf("HTTP response: status=%d, size=%d, time=%dms",
		response.Status, response.Size, response.Time)

	return response, nil
}

// CancelRequest 取消当前请求
func (h *HTTPApp) CancelRequest() {
	log_.Debug("Canceling HTTP request")
	if h.cancelFunc != nil {
		h.cancelFunc()
		h.cancelFunc = nil
	}
}
